package online.shenme.itcast.ui;

import online.shenme.itcast.entity.ExamInfo;
import online.shenme.itcast.entity.QuestionInfo;
import online.shenme.itcast.entity.User;
import online.shenme.itcast.exception.IDPatternException;
import online.shenme.itcast.exception.PWDPatternException;
import online.shenme.itcast.service.ExamService;
import javax.swing.*;
import java.awt.*;
import java.io.Serializable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class ClientContext implements Serializable {
    private static final long serialVersionUID = -3588932108572423199L;
    /**
     * 登录界面
     */
    private LoginFrame loginFrame;
    /**
     * 登录成功后，菜单界面
     */
    private MenuFrame menuFrame;
    private ExamFrame examFrame;
    private WelcomeWindow welcomeWindow;

    private ExamService examService;

    public void setExamService(ExamService examService) {
        this.examService = examService;
    }

    public void setExamFrame(ExamFrame examFrame) {
        this.examFrame = examFrame;
    }

    //IOC
    public void setLoginFrame(LoginFrame loginFrame) {
        this.loginFrame = loginFrame;
    }

    public void setMenuFrame(MenuFrame menuFrame) {
        this.menuFrame = menuFrame;
    }

    public void setWelcomeWindow(WelcomeWindow welcomeWindow) {
        this.welcomeWindow = welcomeWindow;
    }

    public void show() {
        center(welcomeWindow);
        welcomeWindow.setVisible(true);
        final Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                welcomeWindow.setVisible(false);
                center(loginFrame);
                loginFrame.setVisible(true);
                timer.cancel();
            }
        }, 2000);
    }

    /**
     * 登录功能
     */
    private User user;

    public void login() {
        try {
            // 获取界面录入的编号、密码
            String id = loginFrame.getUserId();
            String pwd = loginFrame.getPwd();
            // 调用service 返回登录成功的用户信息
            user = examService.login(id, pwd);

            //登录成功
            loginFrame.setVisible(false);
            // 用户信息更新到登录成功后的界面
            menuFrame.updateView(user);
            center(menuFrame);
            menuFrame.setVisible(true);
        } catch (IDPatternException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(loginFrame, "ID必须是数字!");
        } catch (PWDPatternException e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(loginFrame, "密码需大于6位!");
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(menuFrame, "系统错误:" + e.getMessage());
        }
        //try中还需要抛出一个自定义的异常用来捕捉用户名和密码不对的情况,异常的显示信息模仿NumberFormatException
    }

    /**
     * 退出功能
     */
    public void exit(JFrame from) {
        int val = JOptionPane
                .showConfirmDialog(from, "确定退出【传智考试系统】吗?");
        if (val == JOptionPane.YES_OPTION) {
            System.exit(0);
        }
    }

    /**
     * 当前正在答的题目, 开始考试时候, 初始化为第一题
     * 每次翻页, 更新为新的当前题目
     */
    private QuestionInfo currentQuestion;
    /**
     * 当前考试的状态信息, 在开始考试时候初始化为 考试信息
     */
    private ExamInfo examInfo;

    /**
     * 开始考试功能
     */
    public void start() {
        try {

            /*
                调用examService中的方法
             */
            // 获取考试信息
            examInfo = examService.getExamInfo(user);
            examInfo.setUser(user);
            examService.isExam(user);
            // 获取第一道考题
            currentQuestion = examService.getQustionInfo(0);

            //显示第一题和考试信息
            examFrame.updateView(examInfo, currentQuestion);
            menuFrame.setVisible(false);
            center(examFrame);
            examFrame.setVisible(true);
            startTimer();
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(
                    menuFrame, e.getMessage());
        }
    }

    /**
     * 下一题
     */
    public void next() {
        try {
            //获取到当前题目的index索引
            int index = currentQuestion.getQuestionIndex();
            //获取到用户对当前题目的答案
            List<Integer> userAnswers =
                    examFrame.getUserAnswers();
            /*
             1. 编写service接口实现当前题目的答案的保存-保存到考卷集合对应索引的QuestionInfo中
             2. 编写service接口加载下一个题目
             */
            examService.setQustionInfo(userAnswers, index);
            currentQuestion = examService.next(index + 1);

            examFrame.updateView(examInfo, currentQuestion);
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(
                    examFrame, e.getMessage());
        }
    }

    /**
     * 上一题
     */
    public void prev() {
        try {
            //获取到当前题目的index索引
            int index = currentQuestion.getQuestionIndex();
            //获取到用户对当前题目的答案
            List<Integer> userAnswers =
                    examFrame.getUserAnswers();
            /*
             1. 编写service接口实现当前题目的答案的保存-保存到考卷集合对应索引的QuestionInfo中
             2. 编写service接口加载上一个题目
             */
            examService.setQustionInfo(userAnswers, index);
            currentQuestion = examService.prev(index - 1);

            examFrame.updateView(examInfo, currentQuestion);
        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(
                    examFrame, e.getMessage());
        }
    }

    /**
     * 交卷功能
     */
    public void submit() {
        int val = JOptionPane.showConfirmDialog(examFrame, "确定提交试卷吗?");
        if (val != JOptionPane.YES_OPTION) {
            return;
        }
        // 调用gameOver方法
        gameOver();
    }

    /**
     * 查看得分
     */
    public void result() {
        try {

            int score = examService.queryScore(user); //score 为最终的得分数据

            JOptionPane.showMessageDialog(
                    menuFrame, "考试分数:" + score);

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(
                    menuFrame, e.getMessage());
        }
    }

    private void center(Window win) {
        Toolkit toolkit = Toolkit.getDefaultToolkit();
        Dimension screen = toolkit.getScreenSize();
        int x = (screen.width - win.getWidth()) / 2;
        int y = (screen.height - win.getHeight()) / 2;
        win.setLocation(x, y);
    }

    private Timer timer;

    /**
     * 用户点击开始考试的时候调用该方法完成倒计时功能
     */
    private void startTimer() {
        timer=new Timer();

        //需调用到ExamFrame类中的updateTime方法来更新时间到UI界面
        timer.schedule(new TimerTask() {
            long show = examService.updateTime(examInfo);
            @Override
            public void run() {
                examFrame.updateTime(show-=1000);
                if (show<=0){
                    gameOver();
                }
            }
        },0, 1000);
    }

    /**
     * 交卷调用的功能
     */
    public void gameOver() {
        try {
            if (timer != null) {
                timer.cancel();
            }
            /*
             1. 调用service接口完成最后一道题的答案的保存
             2. 编写service接口完成分数的统计操作并返回最终的分数
               2.1 遍历List<QuestionInfo>集合,该集合中有当前考试题目的答案、分数和用户的答案
               2.2 遍历的过程中判断考试题答案是否和用户的答案完全相等（不管单选还是多选）,如果正确则累加得分
               2.3 计算完成以后保存得分,方便下一次查询
               2.4 可以记录到文本文件中，同时记录当前用户的用户ID
             */


            //获取到当前题目的index索引
            int index = currentQuestion.getQuestionIndex();
            //获取到用户对当前题目的答案
            List<Integer> userAnswers =
                    examFrame.getUserAnswers();
            examService.setQustionInfo(userAnswers, index);

            int score = examService.userScore(examInfo); //最终得分变量

            JOptionPane.showMessageDialog(
                    examFrame, "你的分数:" + score);
            examFrame.setVisible(false);
            center(menuFrame);
            menuFrame.setVisible(true);

        } catch (Exception e) {
            e.printStackTrace();
            JOptionPane.showMessageDialog(
                    examFrame, e.getMessage());
        }
    }
}






